import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

/// 日志过滤器
class LogFilter {
  // 黑名单关键词
  static final List<String> _blacklist = [
    'ImageReader_JNI',
    'Unable to acquire a buffer item',
    'removeInvalidNode',
    'InitSystemFonts',
    'axesSize',
    'DisplayEventDispatcher',
    'ignoring unknown event',
    'jank list'
  ];
  
  // 安装日志过滤器
  static void install() {
    if (!kDebugMode) return; // 只在调试模式下过滤日志
    
    // 重写控制台输出
    _redirectPrintBuffer();
    
    // 重写Flutter错误处理
    _overrideFlutterError();
    
    // 设置平台通道拦截
    _setupPlatformChannelFilter();
    
    // 平台特定处理
    if (Platform.isAndroid) {
      _setupAndroidLogFilter();
    }
  }

  // 重定向打印缓冲区
  static void _redirectPrintBuffer() {
    final originalPrint = debugPrint;
    debugPrint = (String? message, {int? wrapWidth}) {
      if (message != null && !_containsBlacklistedWords(message)) {
        originalPrint(message, wrapWidth: wrapWidth);
      }
    };
  }
  
  // 重写Flutter错误处理
  static void _overrideFlutterError() {
    final originalOnError = FlutterError.onError;
    FlutterError.onError = (FlutterErrorDetails details) {
      if (!_containsBlacklistedWords(details.toString())) {
        originalOnError?.call(details);
      }
    };
  }
  
  // 设置平台通道拦截
  static void _setupPlatformChannelFilter() {
    const MethodChannel('flutter/platform').setMethodCallHandler((call) async {
      if (call.method == 'SystemLogger.printSystemLog' || 
          call.method == 'SystemChrome.systemUIChange') {
        final String message = call.arguments?['message'] ?? '';
        if (_containsBlacklistedWords(message)) {
          return;
        }
      }
      return null;
    });
    
    const MethodChannel('flutter/service_worker').setMethodCallHandler((call) async {
      final String message = call.arguments?.toString() ?? '';
      if (_containsBlacklistedWords(message)) {
        return;
      }
      return null;
    });
  }
  
  // Android特定日志过滤设置
  static void _setupAndroidLogFilter() {
    const MethodChannel('com.playtruly.wanzhende2025/log_filter')
      .invokeMethod('installLogFilter')
      .catchError((_) {});
  }
  
  // 检查消息是否包含黑名单关键词
  static bool _containsBlacklistedWords(String message) {
    return _blacklist.any((word) => message.contains(word));
  }
} 